package com.lagou.web.servlet;

import com.lagou.base.BaseServlet;
import com.lagou.utils.UUIDUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        DiskFileItemFactory factory = new DiskFileItemFactory();

        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setHeaderEncoding("utf-8");

        boolean isMultipart = upload.isMultipartContent(req);
        if (isMultipart) {
            List<FileItem> list = null;
            try {
                list = upload.parseRequest(req);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            if (null != list) {
                for (FileItem fileItem : list) {
                    boolean isFormField = fileItem.isFormField();
                    if (isFormField) {
                        String fieldName = fileItem.getFieldName();
                        String fieldValue = fileItem.getString("utf-8");
                        System.out.println(fieldName + ":" + fieldValue);
                    } else {
                        String name = fileItem.getName();
                        String newFileName = UUIDUtils.getUUID() + "_" + name;

                        String realPath = this.getServletContext().getRealPath("/");
                        String home = realPath.substring(0, realPath.indexOf("lagou_edu_home"));

                        InputStream in = fileItem.getInputStream();
                        FileOutputStream out = new FileOutputStream(home + "/upload/" + newFileName);
                        IOUtils.copy(in, out);
                        out.close();
                        in.close();
                    }
                }
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
